package singleton;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-07-25 15:59
 * @notify
 * @version 1.0
 */

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class KeyGenerator {
    private static KeyGenerator keygen = new KeyGenerator();
    private int key = 0;
    Properties properties;
    //当前返回
    private int nextKey = 1;
    //每次增加多少个
    private int pool = 10;
    //返回最大值
    private int maxKey = pool;

    private KeyGenerator() {
        //初始化加载一次
        properties = new Properties();
        InputStream in = null;
        try {
            in = new FileInputStream("C:\\JavaPattern\\src\\singleton\\KEYDB.properties");
            properties.load(in);
        } catch (Exception e) {
        }
    }

    public static KeyGenerator getInstance() {
        return keygen;
    }

    //简单的获取一个不重复的key
    public synchronized int getNextKey() {
        return key++;
    }

    //每次从db取出key然后在更新key
    public synchronized int getSingNextKey() {
        //获取当前 key
        String key = properties.getProperty("key");
        int rKey = new Integer(key);
        properties.setProperty("key", new Integer(rKey + 1).toString());
        //返回key
        return rKey;
    }

    //每次缓存多个key
    public int getPoolKey() {
        if (nextKey > maxKey) {
            return addKey();
        } else {
            int rKey = nextKey;
            nextKey++;
            return rKey;
        }
    }

    //每次增加10个key
    public synchronized int addKey() {
        //获取当前 key
        String key = properties.getProperty("key2");
        int rKey = new Integer(key);
        properties.setProperty("key2", new Integer(rKey + pool).toString());
        maxKey = rKey + pool;
        nextKey = rKey + 1;
        return nextKey;
    }
}
